<?php
  include("DBConfig.class.php");
  class Province{

    public function getProvince($value){
      //Query Province  $votename, $country, $filter
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $sql = "SELECT ".$value['filter']."
                FROM ".DBConfig::$dbfieldname."
                WHERE ".$value['filter']." IS NOT NULL
                GROUP BY ".$value['filter']."
                ORDER BY ".$value['filter']." ASC";
        $stmt = $db->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setProvinceResponse($response);
        } else{
          $response['errorCode'] = 101;
          $response['errorString'] = "Province not found.";
          //$response['errorString'] = $e->getMessage();
          $this->setProvinceResponse($response);
        }

        /*** close the database connection ***/
        $db = null;
      }catch(PDOException $e) {
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          //$response['errorString'] = $e->getMessage();
          $this->setProvinceResponse($response);
      }
    }


    public function searchProvince($value){
      //Query Province  $votename, $country, $filter
      try {
        $db = new PDO("mysql:host=".DBConfig::$dbhost.";dbname=".DBConfig::$dbname, 
                      DBConfig::$dbuser, 
                      DBConfig::$dbpass, 
                      array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
                  );
        $db->setAttribute( PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION );

        $sql = "SELECT ".$value['filter']."
                FROM ".DBConfig::$dbfieldname."
                WHERE ".$value['filter']." like '%".$value['key']."%'
                GROUP BY ".$value['filter']."
                ORDER BY ".$value['filter']." ASC";
        $stmt = $db->prepare($sql);
        $stmt->execute();

        $result = $stmt->fetchAll();

        if(!empty($result)){
          $response['votename'] = $value['votename'];
          $response['country'] = $value['country'];
          $response['layer'] = $result;
          $response['type'] = "search";
          $response['errorCode'] = 0;
          $response['errorString'] = "ok";
          $this->setProvinceResponse($response);
        } else{
          $response['errorCode'] = 101;
          $response['errorString'] = "Province not found.";
          $this->setProvinceResponse($response);
        }

        /*** close the database connection ***/
        $db = null;
      }catch(PDOException $e) {
          $response['errorCode'] = 5;
          $response['errorString'] = "Database cann't connect";
          echo $e->getMessage();
          $this->setProvinceResponse($response);
      }
    }

    public function setProvinceResponse($response){

        //Gen XML
        $xml = new DOMDocument('1.0', 'UTF-8');
        $xml->formatOutput = true;


        $xml_node_datas = $xml->createElement("Datas");
        $xml->appendChild( $xml_node_datas);

        if($response['errorCode'] == 0){
          $xml_node_country = $xml->createElement("country",$response['country']);
          $xml_node_datas->appendChild( $xml_node_country);

          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
          $count = 1;
          foreach($response['layer'] as $val){

            //Check thai country
            if($response['country'] == "TH"){
              $string = "จังหวัด";
              if(strstr($val['province'],$string)){
                $province = $val['province'];
              }else{
                $province = "จังหวัด".$val['province'];
              }
            }else{
              $province = $val['province'];
            }
            
            $xml_node_data = $xml->createElement("Data");
            $xml_node_data->setAttribute("id", $count++);
            $xml_node_datas->appendChild( $xml_node_data);

            $xml_node_type = $xml->createElement("type","list");
            $xml_node_data->appendChild( $xml_node_type);

            $xml_node_title = $xml->createElement("title", $province);
            $xml_node_data->appendChild( $xml_node_title);

            $arg = array(
                          'pro' => $val['province']
                        );
            $xml_node_xml = $xml->createElement("xml", htmlentities($this->getNextURL("province", "district", $arg)));
            $xml_node_data->appendChild( $xml_node_xml);

          }


        }else{
          $xml_node_errorcode = $xml->createElement( "errorcode", $response['errorCode']);
          $xml_node_datas->appendChild( $xml_node_errorcode );
          $xml_node_errorstring = $xml->createElement( "errorstring", $response['errorString']);
          $xml_node_datas->appendChild( $xml_node_errorstring );
        }

        echo $xml->saveXML();
    }


    public function getNextURL($currentLayer, $nextLayer, $arg){
      $page_url = 'http';
      if ($_SERVER['HTTPS'] == "on") {$pageURL .= "s";}
        $page_url .= "://";
      if ($_SERVER['SERVER_PORT'] != "80") {
        $page_url .= $_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'];
      } else {
        $page_url .= $_SERVER['SERVER_NAME'];
      }
      $explode_uri = explode("&key",$_SERVER['REQUEST_URI']);
      $new_url = str_replace("filter=".$currentLayer, "filter=".$nextLayer, $explode_uri[0]);

      foreach($arg as $key=>$val){
        //$uri[] = $key."=".urlencode(iconv( "ISO-8859-1","UTF-8", $val));
        $uri[] = $key."=".urlencode($val);
      }
      $uri = implode("&", $uri);

      return $page_url.$new_url."&".$uri;
    }
  }




?>